package cn.flying.cloud.flow.core.listener.event.callback;


import javax.annotation.Resource;

import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.flying.cloud.flow.bo.FwProcInstBo;
import cn.flying.cloud.flow.core.enums.FlowStateEnum;
import cn.flying.cloud.flow.service.FwProcInstService;

/**
 * 流程开始监听
 *
 * @author: admin
 * @date: 2023年02月26日 08:20
 * @version: 1.0
 */
@Component
public class ProcessStartedListenerCallback implements EventListenerCallback {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private RuntimeService runtimeService;
    @Resource
    private FwProcInstService procInstService;

    @Override
    public void execute(FlowableEvent event) {
        logger.info("==========流程开始监听器回调处理---start===========");
        logger.info("监听事件类型：【{}】", event.getType().name());
        FlowableEntityEventImpl entityEvent = (FlowableEntityEventImpl) event;
        ExecutionEntityImpl entity = (ExecutionEntityImpl) entityEvent.getEntity();
        // 流程开始，正在审批
        runtimeService.updateBusinessStatus(entityEvent.getProcessInstanceId(), FlowStateEnum.Waiting.getCode());

        FwProcInstBo inst = new FwProcInstBo();
        inst.setProcInstId(entityEvent.getProcessInstanceId());
        inst = procInstService.getOneObj(inst);
        inst.setProcStatus(FlowStateEnum.Waiting.getCode());
        procInstService.updateObj(inst);

        ExecutionEntityImpl parent = entity.getParent();
        logger.info("流程实例【{}】启动成功，流程实例ID：{}，业务流水号：{}，", entity.getProcessDefinitionKey(), entity.getProcessInstanceId(), parent.getBusinessKey());
        logger.info("==========流程开始监听器回调处理---end===========");
    }
}
